package com.rong.DAO;

import com.opensymphony.xwork2.ActionContext;
import com.rong.hibernate.BaseHibernateDAO;
import com.rong.hibernate.Const;

import java.util.List;
import java.util.Map;

import org.hibernate.Transaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;

import com.rong.ORM.ZynBusiInput;
import com.rong.ORM.ZynQueryCriter;
import com.rong.ORM.ZynSell;
import com.rong.ORM.ZynTransfer;
import com.rong.ORM.ZynUser;

/**
 * A data access object (DAO) providing persistence and search support for
 * ZynTransfer entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.rong.DAO.ZynTransfer
 * @author MyEclipse Persistence Tools
 */

public class ZynTransferDAO extends BaseHibernateDAO {
	private static final Log log = LogFactory.getLog(ZynTransferDAO.class);
	BaseHibernateDAO b=new BaseHibernateDAO();
	ZynBusiInputDAO busiDao = new ZynBusiInputDAO();
	// property constants
	public static final String COM_FROM_ID = "comFromId";
	public static final String COM_TO_ID = "comToId";
	public static final String CAR_ID = "carId";
	public static final String TRAN_NUM = "tranNum";
	public static final String STMT_STYLE = "stmtStyle";
	public static final String PRICE_ID = "priceId";
	public static final String PRICE = "price";
	public static final String AMOUNT = "amount";
	public static final String SUM_PLUS = "sumPlus";
	public static final String SUM = "sum";
	public static final String METER_START = "meterStart";
	public static final String METER_END = "meterEnd";
	public static final String REMARK = "remark";
	public static final String EXTATTR1 = "extattr1";
	public static final String EXTATTR2 = "extattr2";
	public static final String EXTATTR3 = "extattr3";
	public static final String EXTATTR4 = "extattr4";
	public static final String EXTATTR_DOUB5 = "extattrDoub5";
	public static final String EXTATTR_DOUB6 = "extattrDoub6";

	public void save(ZynTransfer transientInstance) {
		log.debug("saving ZynTransfer instance");
		try {
			Transaction ts=null;
			ts=getSession().beginTransaction();
			getSession().save(transientInstance);
			ts.commit();
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(ZynTransfer persistentInstance) {
		log.debug("deleting ZynTransfer instance");
		try {
			Transaction ts=null;
			ts=getSession().beginTransaction();
			getSession().delete(persistentInstance);
			ts.commit();
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ZynTransfer findById(java.lang.Integer id) {
		log.debug("getting ZynTransfer instance with id: " + id);
		try {
			ZynTransfer instance = (ZynTransfer) getSession().load(ZynTransfer.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(ZynTransfer instance) {
		log.debug("finding ZynTransfer instance by example");
		try {
			List results = getSession().createCriteria(
					"com.rong.DAO.ZynTransfer").add(Example.create(instance))
					.list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ZynTransfer instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ZynTransfer as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByComFromId(Object comFromId) {
		return findByProperty(COM_FROM_ID, comFromId);
	}

	public List findByComToId(Object comToId) {
		return findByProperty(COM_TO_ID, comToId);
	}

	public List findByCarId(Object carId) {
		return findByProperty(CAR_ID, carId);
	}

	public List findByTranNum(Object tranNum) {
		return findByProperty(TRAN_NUM, tranNum);
	}

	public List findByStmtStyle(Object stmtStyle) {
		return findByProperty(STMT_STYLE, stmtStyle);
	}

	public List findByPriceId(Object priceId) {
		return findByProperty(PRICE_ID, priceId);
	}

	public List findByPrice(Object price) {
		return findByProperty(PRICE, price);
	}

	public List findByAmount(Object amount) {
		return findByProperty(AMOUNT, amount);
	}

	public List findBySumPlus(Object sumPlus) {
		return findByProperty(SUM_PLUS, sumPlus);
	}

	public List findBySum(Object sum) {
		return findByProperty(SUM, sum);
	}

	public List findByMeterStart(Object meterStart) {
		return findByProperty(METER_START, meterStart);
	}

	public List findByMeterEnd(Object meterEnd) {
		return findByProperty(METER_END, meterEnd);
	}

	public List findByRemark(Object remark) {
		return findByProperty(REMARK, remark);
	}

	public List findByExtattr1(Object extattr1) {
		return findByProperty(EXTATTR1, extattr1);
	}

	public List findByExtattr2(Object extattr2) {
		return findByProperty(EXTATTR2, extattr2);
	}

	public List findByExtattr3(Object extattr3) {
		return findByProperty(EXTATTR3, extattr3);
	}

	public List findByExtattr4(Object extattr4) {
		return findByProperty(EXTATTR4, extattr4);
	}

	public List findByExtattrDoub5(Object extattrDoub5) {
		return findByProperty(EXTATTR_DOUB5, extattrDoub5);
	}

	public List findByExtattrDoub6(Object extattrDoub6) {
		return findByProperty(EXTATTR_DOUB6, extattrDoub6);
	}

	public List findAll() {
		log.debug("finding all ZynTransfer instances");
		try {
			String queryString = "from ZynTransfer";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ZynTransfer merge(ZynTransfer detachedInstance) {
		log.debug("merging ZynTransfer instance");
		try {
			Transaction ts=null;
			ts=getSession().beginTransaction();
			ZynTransfer result = (ZynTransfer) getSession().merge(
					detachedInstance);
			ts.commit();
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ZynTransfer instance) {
		log.debug("attaching dirty ZynTransfer instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ZynTransfer instance) {
		log.debug("attaching clean ZynTransfer instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	//以下为分页部分
	/**
	 * 查找并返回所有计划
	 */

	public List<ZynTransfer> findZynTransfertByPage(int page, int rowsPerPage,ZynQueryCriter queryCrt) {
		
		String queryString = "from ZynTransfer";
		Transaction ts2=null;
		ts2=getSession().beginTransaction();
		getSession().clear(); 
		
		ActionContext actionContext = ActionContext.getContext();         
	     Map session = actionContext.getSession(); 
	     ZynUser loginUser=(ZynUser)session.get("loginUser");   //登录用户	
		//Query query =getSession().createQuery("from ZynTransfer order by id desc");
		//query.setMaxResults(rowsPerPage); // 每页最多显示几条
		//query.setFirstResult((page - 1) * rowsPerPage); // 每页从第几条记录开始
		Criteria crt = getSession().createCriteria(ZynTransfer.class);
		crt.addOrder(org.hibernate.criterion.Order.desc("id"));
		

		if(queryCrt.getStartDate()!=null&&queryCrt.getEndDate()!=null){
			crt.add(Restrictions.and(Restrictions.ge("extattrdate2", queryCrt.getStartDate()), Restrictions.le("extattrdate2", queryCrt.getEndDate())));
		}else if(queryCrt.getStartDate()!=null&&queryCrt.getEndDate()==null){
			crt.add(Restrictions.ge("extattrdate2",queryCrt.getStartDate()));	
		}else if(queryCrt.getStartDate()==null&&queryCrt.getEndDate()!=null){
			crt.add(Restrictions.le("extattrdate2", queryCrt.getEndDate()));	
		}
		
		if(queryCrt.getToComId()!=null&&queryCrt.getToComId()>0){			
			crt.add(Restrictions.eq("comToId", queryCrt.getToComId()));
		}
		if(queryCrt.getFromComId()!=null&&queryCrt.getFromComId()>0){			
			crt.add(Restrictions.eq("comFromId", queryCrt.getFromComId()));
		}

		if(queryCrt.getCarId()!=null&&queryCrt.getCarId()>0){			
			crt.add(Restrictions.eq("carId", queryCrt.getCarId()));
		}

		if(queryCrt.getNum()!=null&&!(queryCrt.getNum().equalsIgnoreCase(""))){			
			List<ZynBusiInput> busiList= busiDao.findByNum(queryCrt.getNum());
			if(busiList.size()>0){
				ZynBusiInput temp=busiList.get(0);
				crt.add(Restrictions.eq("extattr2",temp.getId()));
			}
		}
		if(queryCrt.getTransfNum()!=null&&!(queryCrt.getTransfNum().equalsIgnoreCase(""))){			
			crt.add(Restrictions.eq("tranNum", queryCrt.getTransfNum()));
		}
		
		//增加对状态的判断 wafech 2011-05-05
		if(queryCrt.getExtA()!=null&&!(queryCrt.getExtA().equalsIgnoreCase(""))){			
			crt.add(Restrictions.eq("extattr3", Integer.parseInt(queryCrt.getExtA())));
		}
		
		//end
		//--权限判断,分公司只能看本公司单据，本部可以查看全部		
		if(loginUser.getZyncom().getComProperty().equalsIgnoreCase(Const.comTypetop)){			
			//总部
		}else{			
			crt.add(Restrictions.eq("extattr4", loginUser.getComId()));  //匹配单据的所属公司
		}
		
		crt.setMaxResults(rowsPerPage); // 每页最多显示几条
		crt.setFirstResult((page - 1) * rowsPerPage); // 每页从第几条记录开始
		ts2.commit();
		List<ZynTransfer> list = crt.list();
		for (int i = 0; i < list.size(); i++) {
			
			System.out.println("*****transfer dao*******sell id=:"+ list.get(i).getId()+"==Extattr2:"+list.get(i).getExtattr2()+"==busiinput:"+list.get(i).getBusiInput().getId()+"==num:"+list.get(i).getBusiInput().getNum()+"==status:"+list.get(i).getSellSts().getName());
			System.out.println("*****transfer dao*******sell id=:"+ list.get(i).getId()+"==from com2:"+list.get(i).getFromComObj().getComName()+"==to com:"+list.get(i).getToComObj().getComName()+"==car:"+list.get(i).getCarObj().getNum());
			
		}
        
		

		return list;
	}
	/**
	 * 查找并返回所有计划
	 */

	public List<ZynTransfer> tatolRows(ZynQueryCriter queryCrt) {
		getSession().clear();
		
		ActionContext actionContext = ActionContext.getContext();         
	     Map session = actionContext.getSession(); 
	     ZynUser loginUser=(ZynUser)session.get("loginUser");   //登录用户	
		//Query query =getSession().createQuery("from ZynTransfer order by id desc");
		//query.setMaxResults(rowsPerPage); // 每页最多显示几条
		//query.setFirstResult((page - 1) * rowsPerPage); // 每页从第几条记录开始
		Criteria crt = getSession().createCriteria(ZynTransfer.class);
		crt.addOrder(org.hibernate.criterion.Order.desc("id"));
		

		if(queryCrt.getStartDate()!=null&&queryCrt.getEndDate()!=null){
			crt.add(Restrictions.and(Restrictions.ge("extattrdate2", queryCrt.getStartDate()), Restrictions.le("extattrdate2", queryCrt.getEndDate())));
		}else if(queryCrt.getStartDate()!=null&&queryCrt.getEndDate()==null){
			crt.add(Restrictions.ge("extattrdate2",queryCrt.getStartDate()));	
		}else if(queryCrt.getStartDate()==null&&queryCrt.getEndDate()!=null){
			crt.add(Restrictions.le("extattrdate2", queryCrt.getEndDate()));	
		}
		
		
		if(queryCrt.getToComId()!=null&&queryCrt.getToComId()>0){			
			crt.add(Restrictions.eq("comToId", queryCrt.getToComId()));
		}
		if(queryCrt.getFromComId()!=null&&queryCrt.getFromComId()>0){			
			crt.add(Restrictions.eq("comFromId", queryCrt.getFromComId()));
		}

		if(queryCrt.getCarId()!=null&&queryCrt.getCarId()>0){			
			crt.add(Restrictions.eq("carId", queryCrt.getCarId()));
		}

		if(queryCrt.getNum()!=null&&!(queryCrt.getNum().equalsIgnoreCase(""))){			
			List<ZynBusiInput> busiList= busiDao.findByNum(queryCrt.getNum());
			if(busiList.size()>0){
				ZynBusiInput temp=busiList.get(0);
				crt.add(Restrictions.eq("extattr2",temp.getId()));
			}
		}
		if(queryCrt.getTransfNum()!=null&&!(queryCrt.getTransfNum().equalsIgnoreCase(""))){			
			crt.add(Restrictions.eq("tranNum", queryCrt.getTransfNum()));
		}
		//增加对状态的判断 wafech 2011-05-05
		if(queryCrt.getExtA()!=null&&!(queryCrt.getExtA().equalsIgnoreCase(""))){			
			crt.add(Restrictions.eq("extattr3", Integer.parseInt(queryCrt.getExtA())));
		}
		
		//end
		
		//--权限判断,分公司只能看本公司单据，本部可以查看全部		
		if(loginUser.getZyncom().getComProperty().equalsIgnoreCase(Const.comTypetop)){			
			//总部
		}else{			
			crt.add(Restrictions.eq("extattr4", loginUser.getComId()));  //匹配单据的所属公司
		}
		
		List<ZynTransfer> list = crt.list();
		return list;
	}
	
}